package com.zhao.service.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhao.base.TokenThread;
import com.zhao.push.Data;
import com.zhao.push.PushMessage;
import com.zhao.service.PushMessageService;
import com.zhao.util.HttpRequest;
import com.zhao.util.StringUtil;

import net.sf.json.JSONObject;

public class PushMessageServiceImpl implements PushMessageService{
	Logger log=LoggerFactory.getLogger(PushMessageServiceImpl.class);
	private String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	
	@Override
	public void pushMessage(Map<String,Object> map,String[] openIds,Data data) {
		PushMessage push=new PushMessage();
		requestUrl=requestUrl.replace("ACCESS_TOKEN",TokenThread.accessToken.getAccessToken());
		
		String type=(String) map.get("type");//0(模板跳转链接) 1(跳转到小程序) 空为不做任何操作
		String templateId=(String) map.get("templateId");
		push.setTemplate_id(templateId);
		push.setData(data);
		
		if(!StringUtil.isEmpty(type)) {
			if("0".equals(type)) {
				String url=(String) map.get("url");
				push.setUrl(url);
			}else {//跳转小程序
				String pagepath=(String) map.get("pagepath");
				String appid=(String) map.get("appid");//小程序的appid
				push.setPagepath(pagepath);
				push.setAppid(appid);
			}
		}
		
		for(int i=0;i<openIds.length;i++) {
			push.setTouser(openIds[i]);
			String json=JSONObject.fromObject(push).toString();
			JSONObject result=null;
			try {
				result=HttpRequest.httpsRequest(requestUrl, "POST", json);
				String errmsg=result.getString("errmsg");
				if("ok".equals(errmsg)) {
					log.info("模板发送成功"+i);
				}else {
					log.info("模板发送失败"+i);
				}
			} catch (Exception e) {
				log.info("模板发送异常"+i);
				continue;
			}
		}
	}
}
